import { createFileRoute } from '@tanstack/react-router'
import { useState, useEffect } from 'react'
import { Card, Tabs, Typography, Space, Tag, Divider, Skeleton } from 'antd'
import { HeartOutlined, DownloadOutlined, TrophyOutlined, ClockCircleOutlined } from '@ant-design/icons'
import { movieServiceApi } from '@/api'
import styles from './index.module.less'

const { Title, Text } = Typography
const { TabPane } = Tabs

// 电影类型定义
interface MovieItem {
  id: number
  title: string
  coverUrl: string
  rating: number
  publishTime: string
  likeCount: number
  downloadCount: number
  category: string
}

export const Route = createFileRoute('/movie/rank/')({
  component: RouteComponent,
})

function RouteComponent() {
  const [likeRankMovies, setLikeRankMovies] = useState<MovieItem[]>([])
  const [downloadRankMovies, setDownloadRankMovies] = useState<MovieItem[]>([])
  const [loading, setLoading] = useState(true)

  // 获取排行榜数据
  useEffect(() => {
    fetchRankData()
  }, [])

  // 模拟获取排行榜数据
  const fetchRankData = async () => {
    try {
      setLoading(true)
      // 这里应该从API获取真实数据，但为了演示，我们使用模拟数据
      // const result = await movieServiceApi.getMovieRank()
      
      // 模拟数据
      const mockMovies = Array.from({ length: 10 }, (_, i) => ({
        id: i + 1,
        title: `电影标题 ${i + 1}`,
        coverUrl: `https://picsum.photos/300/450?random=${i}`,
        rating: parseFloat((Math.random() * 2 + 8).toFixed(1)),
        publishTime: `${2020 + Math.floor(Math.random() * 4)}-${String(Math.floor(Math.random() * 12) + 1).padStart(2, '0')}`,
        likeCount: Math.floor(Math.random() * 10000) + 1000,
        downloadCount: Math.floor(Math.random() * 50000) + 5000,
        category: ['动作', '科幻', '喜剧', '冒险', '爱情', '悬疑', '惊悚'][Math.floor(Math.random() * 7)]
      }))
      
      // 按点赞数排序
      const likeSorted = [...mockMovies].sort((a, b) => b.likeCount - a.likeCount)
      // 按下载数排序
      const downloadSorted = [...mockMovies].sort((a, b) => b.downloadCount - a.downloadCount)
      
      setLikeRankMovies(likeSorted)
      setDownloadRankMovies(downloadSorted)
    } catch (error) {
      console.error('获取排行榜数据失败:', error)
    } finally {
      setLoading(false)
    }
  }

  // 格式化数字显示
  const formatNumber = (num: number): string => {
    if (num >= 10000) {
      return (num / 10000).toFixed(1) + '万'
    }
    return num.toString()
  }

  // 渲染排名标识
  const renderRankBadge = (index: number) => {
    if (index === 0) {
      return <div className={styles.rankGold}><TrophyOutlined /> 1</div>
    } else if (index === 1) {
      return <div className={styles.rankSilver}><TrophyOutlined /> 2</div>
    } else if (index === 2) {
      return <div className={styles.rankBronze}><TrophyOutlined /> 3</div>
    } else {
      return <div className={styles.rankNumber}>{index + 1}</div>
    }
  }

  // 渲染电影卡片
  const renderMovieCard = (movie: MovieItem, index: number) => {
    const isTopRank = index < 3
    
    return (
      <Card
        key={movie.id}
        hoverable
        cover={
          <div className={styles.movieCover}>
            {renderRankBadge(index)}
            <img 
              alt={movie.title}
              src={movie.coverUrl}
              className={styles.coverImage}
              loading="lazy"
            />
            <div className={styles.movieOverlay}></div>
          </div>
        }
        className={`${styles.movieCard} ${isTopRank ? styles.topRankCard : ''}`}
        bodyStyle={{ padding: 0 }}
      >
        <div className={styles.movieInfo}>
          <div className={styles.movieTitleRow}>
            <Title level={5} className={styles.movieTitle}>{movie.title}</Title>
            <Tag className={styles.ratingTag}>{movie.rating}</Tag>
          </div>
          
          <div className={styles.movieMeta}>
            <Tag className={styles.categoryTag}>{movie.category}</Tag>
            <Text className={styles.publishTime}>
              <ClockCircleOutlined />
              {movie.publishTime}
            </Text>
          </div>
          
          <div className={styles.statsRow}>
            <div className={styles.statsItem}>
              <HeartOutlined className={styles.statIcon} />
              <Text className={styles.statValue}>{formatNumber(movie.likeCount)}</Text>
            </div>
            <div className={styles.statsItem}>
              <DownloadOutlined className={styles.statIcon} />
              <Text className={styles.statValue}>{formatNumber(movie.downloadCount)}</Text>
            </div>
          </div>
        </div>
      </Card>
    )
  }

  // 渲染骨架屏
  const renderSkeleton = () => {
    return Array.from({ length: 6 }).map((_, index) => (
      <Card key={index} className={styles.movieCard}>
        <Skeleton active avatar paragraph={{ rows: 4 }} />
      </Card>
    ))
  }

  return (
    <div className={styles.rankPage}>
      <div className={styles.content}>
        {/* 页面标题 */}
        <div className={styles.header}>
          <Title className={styles.pageTitle}>电影排行榜</Title>
          <Text type="secondary" className={styles.pageSubtitle}>
            查看最受欢迎和最多下载的电影
          </Text>
        </div>

        {/* 排行榜选项卡 */}
        <Tabs 
          defaultActiveKey="1" 
          className={styles.tabs}
          tabBarStyle={{
            marginBottom: '32px',
            borderBottom: '2px solid #f0f0f0'
          }}
        >
          {/* 点赞排行榜 */}
          <TabPane 
            tab={<Space size="small"><HeartOutlined /> 点赞排行榜</Space>} 
            key="1"
            className={styles.tabContent}
          >
            <div className={styles.movieGrid}>
              {loading ? renderSkeleton() : likeRankMovies.map((movie, index) => renderMovieCard(movie, index))}
            </div>
          </TabPane>

          {/* 下载排行榜 */}
          <TabPane 
            tab={<Space size="small"><DownloadOutlined /> 下载排行榜</Space>} 
            key="2"
            className={styles.tabContent}
          >
            <div className={styles.movieGrid}>
              {loading ? renderSkeleton() : downloadRankMovies.map((movie, index) => renderMovieCard(movie, index))}
            </div>
          </TabPane>
        </Tabs>

        {/* 排行榜介绍 */}
        <div className={styles.rankInfoSection}>
          <Title level={4}>排行榜说明</Title>
          <Divider className={styles.divider} />
          <div className={styles.infoText}>
            <p>排行榜数据每24小时更新一次，点赞排行榜展示了用户最喜欢的电影，下载排行榜展示了最受欢迎的电影资源。</p>
            <p>点击电影卡片可查看电影详情，前三名的电影会有特殊的标记和动画效果。</p>
          </div>
        </div>
      </div>
    </div>
  )
}
